﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;
using System.Collections.ObjectModel;
using CookComputing.XmlRpc;
using System.Reflection;

namespace HomeWP
{
    public partial class Functions : PhoneApplicationPage
    {
        private MainPage.HMDataContext hMDB;
        private ObservableCollection<DeviceFunction> _hMDeviceFunctions;
        private CCUSettings CCUSet;

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        // Used to notify Silverlight that a property has changed.
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        public ObservableCollection<DeviceFunction> HMFunctions
        {
            get
            {
                return _hMDeviceFunctions;
            }
            set
            {
                if (_hMDeviceFunctions != value)
                {
                    _hMDeviceFunctions = value;
                    NotifyPropertyChanged("HMFunctions");
                }
            }
        }

        public Functions()
        {
            InitializeComponent();

            // Create the database if it does not exist.
            using (MainPage.HMDataContext db = new MainPage.HMDataContext(MainPage.HMDataContext.DBConnectionString))
            {
                if (db.DatabaseExists() == false)
                {
                    //Create the database
                    db.CreateDatabase();
                }
            }
            
            // Connect to the database and instantiate data context.
            hMDB = new MainPage.HMDataContext(MainPage.HMDataContext.DBConnectionString);

            if (hMDB.HMCCUSettings.Count(t => t.ConfigID == "TEST") > 0)
            {
                CCUSet = hMDB.HMCCUSettings.Single(t => t.ConfigID == "TEST");
            }

            // Data context and observable collection are children of the main page.
            this.DataContext = this;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            // Execute the query and place the results into a collection.
            HMFunctions = new ObservableCollection<DeviceFunction>(from DeviceFunction oItem in hMDB.HMFunction select oItem);
            pivFunctions.Items.Clear();

            try
            {
                if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    MessageBox.Show("Keine Netzerkverbindung vorhanden... !", "Verbindungsfehler", MessageBoxButton.OK);
                    return;
                }
                
                List<string> lFunctions = new List<string>();
                foreach (DeviceFunction dFunct in hMDB.HMFunction.OrderBy(t => t.Function).ToList())
                {
                    if (!lFunctions.Contains(dFunct.Function))
                    {
                        var pivotItem1 = new PivotItem();
                        pivotItem1.Header = dFunct.Function;
                        lFunctions.Add(dFunct.Function);
                        pivFunctions.Items.Add(pivotItem1);
                    }
                }

                foreach (PivotItem pivotItem1 in pivFunctions.Items)
                {
                    string sFunction = pivotItem1.Header.ToString();
                    StackPanel sp1 = new StackPanel();
                    List<String> oItems = hMDB.HMFunction.Where(t => t.Function == sFunction).Select(t => t.Address).ToList();
                    //Dictionary<string, string> oResult = new Dictionary<string, string>();
                    oItems.Sort();
                    List<Device> FunctionItems = new List<Device>();
                    foreach (string sAddr in oItems)
                    {
                        try
                        {
                            Device oDevice = hMDB.HMDevices.Single(t => t.Address == sAddr);
                            FunctionItems.Add(oDevice);
                        }
                        catch (Exception ex)
                        {
                            ex.Message.ToString();
                        }
                    }

                    foreach (Device oDevice in FunctionItems.OrderBy(t => t.DisplayName).ThenBy(t => t.Type))
                    {
                        //Add Devices
                        if (oDevice.Type == "SWITCH")
                        {
                            SWITCH tb1 = new SWITCH();
                            tb1.Address = oDevice.Address;
                            tb1.DisplayName = oDevice.DisplayName;
                            tb1.CCUIP = CCUSet.CCU;
                            if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                tb1.CCUPort = 2001;
                            else
                                tb1.CCUPort = 2000;
                            sp1.Children.Add(tb1);
                        }

                        if (oDevice.Type == "DIMMER")
                        {
                            DIMMER tb1 = new DIMMER();
                            tb1.Address = oDevice.Address;
                            tb1.DisplayName = oDevice.DisplayName;
                            tb1.CCUIP = CCUSet.CCU;
                            if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                tb1.CCUPort = 2001;
                            else
                                tb1.CCUPort = 2000;
                            sp1.Children.Add(tb1);
                        }

                        /*if (oDevice.Type == "SMOKE_DETECTOR")
                        {
                            SmokeDetector tb1 = new SmokeDetector();
                            tb1.Address = oDevice.Address;
                            tb1.DisplayName = oDevice.DisplayName;
                            tb1.CCUIP = CCUSet.CCU;
                            if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                tb1.CCUPort = 2001;
                            else
                                tb1.CCUPort = 2000;
                            sp1.Children.Add(tb1);
                        }*/

                        if (oDevice.Type == "SMOKE_DETECTOR_TEAM")
                        {
                            SmokeDetector tb1 = new SmokeDetector();
                            tb1.Address = oDevice.Address;
                            tb1.DisplayName = oDevice.DisplayName;
                            tb1.CCUIP = CCUSet.CCU;
                            if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                tb1.CCUPort = 2001;
                            else
                                tb1.CCUPort = 2000;
                            sp1.Children.Add(tb1);
                        }

                        if (oDevice.Type == "WEATHER")
                        {
                            HMWeather tb1 = new HMWeather();
                            tb1.Address = oDevice.Address;
                            tb1.DisplayName = oDevice.DisplayName;
                            tb1.HMDevice = oDevice;
                            tb1.CCUIP = CCUSet.CCU;
                            if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                tb1.CCUPort = 2001;
                            else
                                tb1.CCUPort = 2000;

                            sp1.Children.Add(tb1);
                        }

                        if (oDevice.Type == "BLIND")
                        {
                            BLIND tb1 = new BLIND();
                            tb1.Address = oDevice.Address;
                            tb1.DisplayName = oDevice.DisplayName;
                            tb1.HMDevice = oDevice;
                            tb1.CCUIP = CCUSet.CCU;
                            if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                tb1.CCUPort = 2001;
                            else
                                tb1.CCUPort = 2000;

                            sp1.Children.Add(tb1);
                        }

                        if (oDevice.Type == "KEY")
                        {
                            HMKey tb1 = new HMKey();
                            tb1.Address = oDevice.Address;
                            tb1.CCUIP = CCUSet.CCU;
                            if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                tb1.CCUPort = 2001;
                            else
                                tb1.CCUPort = 2000;
                            if (oDevice.DisplayName.Contains(':'))
                            {
                                tb1.DisplayName = oDevice.DisplayName.Split(':')[0];
                                tb1._button.Content = oDevice.DisplayName.Split(':')[1];
                            }
                            else
                            {
                                tb1.DisplayName = oDevice.DisplayName;
                            }
                            tb1.HMDevice = oDevice;

                            sp1.Children.Add(tb1);
                        }

                        if (oDevice.Type == "MOTION_DETECTOR")
                        {
                            HMMDIR tb1 = new HMMDIR();
                            tb1.Address = oDevice.Address;
                            tb1.DisplayName = oDevice.DisplayName;
                            tb1.HMDevice = oDevice;
                            tb1.CCUIP = CCUSet.CCU;
                            if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                tb1.CCUPort = 2001;
                            else
                                tb1.CCUPort = 2000;
                            sp1.Children.Add(tb1);
                        }

                        if (oDevice.Type == "INPUT_OUTPUT")
                        {
                            //Output
                            if (oDevice.Direction == 2)
                            {
                                SWITCH tb1 = new SWITCH();
                                tb1.Address = oDevice.Address;
                                tb1.DisplayName = oDevice.DisplayName;
                                tb1.CCUIP = CCUSet.CCU;
                                if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                    tb1.CCUPort = 2001;
                                else
                                    tb1.CCUPort = 2000;
                                sp1.Children.Add(tb1);
                            }
                        }

                        if (oDevice.Type == "SHUTTER_CONTACT")
                        {
                            SHUTTERCONTACT tb1 = new SHUTTERCONTACT();
                            tb1.Address = oDevice.Address;
                            tb1.DisplayName = oDevice.DisplayName;
                            tb1.CCUIP = CCUSet.CCU;
                            if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                tb1.CCUPort = 2001;
                            else
                                tb1.CCUPort = 2000;
                            sp1.Children.Add(tb1);
                        }

                        if (oDevice.Type == "ROTARY_HANDLE_SENSOR")
                        {
                            ROTARYHANDLE tb1 = new ROTARYHANDLE();
                            tb1.Address = oDevice.Address;
                            tb1.DisplayName = oDevice.DisplayName;
                            tb1.CCUIP = CCUSet.CCU;
                            if (string.Compare(oDevice.Bus, "RF", StringComparison.InvariantCultureIgnoreCase) == 0)
                                tb1.CCUPort = 2001;
                            else
                                tb1.CCUPort = 2000;
                            sp1.Children.Add(tb1);
                        }

                        //Add Separator
                        if (sp1.Children.Count > 0)
                        {
                            if (sp1.Children.Last().GetType() != typeof(HMSeparator))
                            {
                                sp1.Children.Add(new HMSeparator());
                            }
                        }
                    }

                    ScrollViewer sc1 = new ScrollViewer();
                    sc1.Content = sp1;
                    pivotItem1.Content = sc1;

                }

                // Call the base method.
                base.OnNavigatedTo(e);
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }

    }
}